﻿using System;

namespace BuildIncrement {
    /// <summary>
    /// DateSpan class used to computer difference of two dates
    /// </summary>
    public class DateSpan {
        /// <summary>
        /// Difference in days
        /// </summary>
        public int Days { get; set; }
        /// <summary>
        /// Difference in months
        /// </summary>
        public int Months { get; set; }
        /// <summary>
        /// Difference in years
        /// </summary>
        public int Years { get; set; }
    }

    /// <summary>
    /// Extensions methods which are available if you are using VS2008
    /// </summary>
    public static class DateDifferenceExtension {
        /// <summary>
        /// Returns difference of two dates
        /// </summary>
        /// <param name="date">DateTime on which extension method is used</param>
        /// <param name="dateToCompare">The second date to compare difference with</param>
        /// <returns>return DateSpan instance of the calculated date difference</returns>
        /// <remarks>The computation always is date - dateToCompare, so dateToCompare should be
        /// lesser than date. If it is not, the answer is always a little bit... ahem... weird.</remarks>
        public static DateSpan DateDifference(this DateTime date, DateTime dateToCompare) {
            var totalMonths = ((date.Year - dateToCompare.Year) * 12) +
                              date.Month - dateToCompare.Month;

            var days = 0;

            if (date.Day < dateToCompare.Day) {
                int day, month, year;

                day = dateToCompare.Day;
                if (date.Month == 1) {
                    month = 12;
                    year = date.Year - 1;
                }
                else {
                    month = date.Month - 1;
                    year = date.Year;
                }

                var dateCalculator = new DateTime(year, month, day);

                days = (date - dateCalculator).Days;

                totalMonths--;
            }
            else {
                days = date.Day - dateToCompare.Day;
            }

            var ds = new DateSpan {
                Years = totalMonths / 12,
                Months = totalMonths % 12,
                Days = days
            };

            return ds;
        }
    }
}
